
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/electronic_key/widgets/detail/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/electronic_key/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/lock/electronic_key/widgets/send_key/index.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class ElectronicKey extends StatefulWidget {
  final int lockId;
  const ElectronicKey({super.key, required this.lockId});

  @override
  State<StatefulWidget> createState() => _ElectronicKeyState();

}

class _ElectronicKeyState extends State<ElectronicKey> {
  final ScrollController _scrollController = ScrollController();
  final List<String> _items = ["重置"];
  List _list = [];
  bool _isLoading = false;
  int _total = 0;
  Map<String, dynamic> _params = {
    "pageNum": 1,
    "pageSize": 10,
    "lockId": null,
  };

  void _getKeyList() async {
    EasyLoading.show();
    _isLoading = true;
    Map resData = await lockApi.getKeyList(widget.lockId, _params);
    _isLoading = false;
    EasyLoading.dismiss();
    setState(() {
      _total = resData["total"] ?? 0;
      _list = resData["rows"] ?? [];
    });
  }

  Future<void> _resetKey() async {
    /// 重置钥匙 清空锁内所有钥匙
    /// 添加登录密码确认重置
    taiDialog(
      context: context,
      title: "确定重置钥匙？",
      child: const Text("重置钥匙后，锁内所有钥匙将被清空，请谨慎操作。", textAlign: TextAlign.center,),
      onConfirm: (BuildContext taiContext) async {
        try {
          EasyLoading.show();
          await lockApi.resetKey(widget.lockId);
          EasyLoading.showToast("重置钥匙成功");
          Stacker.pop(taiContext);
          await Future.delayed(const Duration(seconds: 1));
          _refresh();
        } catch (error) {
          print("error: $error");
        }
      },
    );
  }

  Future<void> _delKey(int lockId, int keyId) async {
    /// 删除钥匙
    taiDialog(
      context: context,
      title: "确定删除钥匙？",
      child: const Text("删除钥匙后，钥匙将无法使用。",textAlign: TextAlign.center,),
      onConfirm: (BuildContext taiContext) async {
        try {
          EasyLoading.show();
          await lockApi.deleteKey(lockId, keyId);
          EasyLoading.showToast("删除钥匙成功");
          Stacker.pop(taiContext);
          await Future.delayed(const Duration(seconds: 1));
          _refresh();
        } catch (error) {
          print("error: $error");
        }
      },
    );
  }

  Future<void> _refresh() async {
    _params["pageNum"] = 1;
    _list = [];
    _getKeyList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getKeyList();
      });
    }
  }

  Widget _listItem(Map item) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Stacker.pushNamed(Keys.DEVICE_LOCK_ELECTRONICKEY_DETAIL, arguments: item);
      },
      onLongPress: () {
        _delKey(int.parse(item["lock"]["lockId"]), item["keyId"]);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(5)),
          color: Colors.white,
        ),
        child: Row(
          children: [
            DecoratedBox(
              decoration: BoxDecoration(
                color: ThemeVars.colorBackground,
                borderRadius: BorderRadius.all(Radius.circular(50)),
              ),
              child: Icon(Icons.person, size: 50,),
            ),
            SizedBox(width: 10,),
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(item["keyName"]),
                    SizedBox(height: 4,),
                    Row(
                      children: [
                        Text(DateTools.formatYMD(item["date"], format: "{y}-{m}-{d} {h}:{i}"), style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 13),),
                        SizedBox(width: 10,),
                        Text(item["keyStatusName"], style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 13),),
                      ],
                    )
                  ],
                )
            )
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _params["lockId"] = widget.lockId;
    _getKeyList();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "电子钥匙",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      showSearch: false,
      actions: [
        // IconButton(
        //   icon: const Icon(Icons.more_horiz),
        //   onPressed: () {
        //     print("点击了gengduo");
        //   },
        // ),
        DropdownButton(
          icon: const Padding(padding: EdgeInsets.only(right: 12), child: Icon(Icons.more_horiz, color: Colors.white,),),
          underline: const SizedBox(height: 0,),
          padding: EdgeInsets.all(0),
          onChanged: (value) {
            if (value == "重置") {
              _resetKey();
            }
          },
          items: _items.map((item) {
            return DropdownMenuItem(
              value: item,
              child: SizedBox(
                height: 20,
                child: Text(item),
              ),
            );
          }).toList(),
        ),
      ],
      floatOnPress: () {
        Stacker.pushNamed(Keys.DEVICE_LOCK_ELECTRONICKEY_SEND_KEY, arguments: widget.lockId)
          .then((refresh) {
            if (refresh != null && refresh as bool) {
              _getKeyList();
            }
        });
      },
      children: [
        Positioned(
          width: MediaQuery.of(context).size.width,
          top: 0,
          left: 0,
          child: Container(
            width: MediaQuery.of(context).size.width,
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
            child: const SizedBox(
              height: 40,
              child: TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    borderSide: BorderSide.none
                  ),
                  hintText: "请输入",
                  isDense: true,
                  filled: true,
                  fillColor: ThemeVars.colorBackground,
                  suffixIcon: SizedBox(
                    child: Icon(Icons.search, size: 20,),
                  ),
                ),
                style: TextStyle(fontSize: 14),
              ),
            )
          )
        ),
        Container(
          width: MediaQuery.of(context).size.width,
          margin: const EdgeInsets.only(top: 60, left: ThemeVars.paddingPage, right: ThemeVars.paddingPage),
          child: RefreshIndicator(
            onRefresh: _refresh,
            child: _list.isEmpty ? ListView(
              children: [EmptyData()],
            ) : ListView.separated(
              controller: _scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              itemBuilder: (BuildContext context, int index) {
                return _listItem(_list[index]);
              },
              separatorBuilder: (BuildContext context, int index) => const SizedBox(height: 12,),
              itemCount: _list.length,
            )
          ),
        )
      ]
    );
  }

}